/**
* A checkbox manager for administrator backend list page
*
* $Id: EtCheckboxes.js 23 2007-08-28 10:08:53Z etng2004 $
* @version $Revision: 1.1 $
* @author etng (etng2004#gmail.com)
*/
String.prototype.quote = function (s)
{
	return s + this + s;
}
var EtCheckboxes = function(parent, prefix, selected){
	this.prefix = 'fields_id_';
	this.parent = document;
	this.checkboxes = [];
	this.selected=[];
	this.init = function(parent, prefix, selected)
	{
		// determin the root element
		if(typeof parent == 'string')parent = document.getElementById(parent);
		if(parent)this.parent = parent;

		if(typeof prefix == 'string')this.prefix = prefix;
		s_selected = selected.join(',').quote(',');

		var inputs = this.parent.getElementsByTagName('INPUT');
		for(var i=0,m=inputs.length;i<m;i++)
		{
			if(inputs[i].type != 'checkbox')continue;
			if(inputs[i].id.substr(0, this.prefix.length)!=this.prefix)continue;
			var id = inputs[i].id.substr(this.prefix.length);
			this.selected = [];
			if(!isNaN(parseInt(id)))
			{
				inputs[i].checked = (s_selected.lastIndexOf(id.quote(','))+1)?true:false;
				this.checkboxes[this.checkboxes.length] = id;
				this.bindEvent(inputs[i], this);
				if(inputs[i].checked)this.selected[this.selected.length] = id;
			}
		}

	};
	this.bindEvent = function(obj, pFunction)
	{
		obj.onclick = function(e)
		{
			var obj = e?e.target:window.event.srcElement;
			pFunction.selected = [];
			for(var i=0,m=pFunction.checkboxes.length;i<m;i++)
			{
				var obj = document.getElementById(pFunction.prefix + pFunction.checkboxes[i]);
				if(obj.checked)pFunction.selected[pFunction.selected.length] = pFunction.checkboxes[i];
			}
		}
	};
	this.clear = function()
	{
		this.selected = [];
		for(var i=0,m=this.checkboxes.length;i<m;i++)
		{
			var obj = document.getElementById(this.prefix + this.checkboxes[i]);
			obj.checked = false;
		}
	};
	this.inverse = function()
	{
		this.selected = [];
		for(var i=0,m=this.checkboxes.length;i<m;i++)
		{
			var obj = document.getElementById(this.prefix + this.checkboxes[i]);
			obj.checked = !obj.checked;
			if(obj.checked)this.selected[this.selected.length] = this.checkboxes[i];
		}
	};
	this.all = function()
	{
		this.selected = [];
		for(var i=0,m=this.checkboxes.length;i<m;i++)
		{
			var obj = document.getElementById(this.prefix + this.checkboxes[i]);
			obj.checked = true;
			this.selected[this.selected.length] = this.checkboxes[i];
		}
	};
	this.init(parent, prefix, selected);
};